package com.lqg.bookLibrary.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.lqg.bookLibrary.common.core.domain.JsonResult;
import com.lqg.bookLibrary.common.myInterface.CurrentUser;
import com.lqg.bookLibrary.common.myInterface.CurrentUserPojo;
import com.lqg.bookLibrary.common.util.DateHelper;
import com.lqg.bookLibrary.pojo.Books;
import com.lqg.bookLibrary.pojo.Borrow;
import com.lqg.bookLibrary.pojo.Collect;
import com.lqg.bookLibrary.pojo.Score;
import com.lqg.bookLibrary.service.IBooksService;
import com.lqg.bookLibrary.service.IBorrowService;
import com.lqg.bookLibrary.service.ICollectService;
import com.lqg.bookLibrary.service.IScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/borrow")
@CrossOrigin
public class BorrowController {

    @Autowired
    private IBorrowService borrowService;

    @Autowired
    private IBooksService booksService;

    @Autowired
    private IScoreService scoreService;

    @GetMapping("/list")
    public JsonResult getListById(@CurrentUser CurrentUserPojo userPojo) {
        Long userId = userPojo.getUserId();
        List<Borrow> list = borrowService.lambdaQuery().eq(Borrow::getUserId, userId).list();

        if (list.size() == 0) {
            return JsonResult.success();
        }

        List<Books> booksList = booksService.lambdaQuery().in(Books::getBookId,
                list.stream().map(x -> x.getBookId()).collect(Collectors.toList())
        ).list();

        List<JSONObject> result = new ArrayList<>();

        result = list.stream().map(x -> {
            Books books = booksList.stream().filter(y -> Objects.equals(y.getBookId(), x.getBookId()))
                    .findFirst().get();

            LocalDateTime localDateTime = x.getCreatedAt().plusDays(x.getTimeLimit());
            LocalDateTime now = LocalDateTime.now();
            String status = "";
            String remarks = "";
            if (localDateTime.isAfter(now)) {
                long between = ChronoUnit.DAYS.between(now, localDateTime);
                if (between <= 1){
                    status = "期限不多,尽快归还";
                }else {
                    status = "借阅中";
                }
            }else {
                status = "已逾期";
            }

            if (x.getOverdue() == 1) {
                remarks = "已逾期";
            }
            if (x.getDelay() == 1){
                remarks = "已申请延期,请在期限内尽快归还!";
            }
            if (x.getReturnAt() != null) {
                remarks = "已还书";
                status = "已还书";
            }


            JSONObject jsonObject = new JSONObject();
            jsonObject.put("borrowId",x.getBorrowId());
            jsonObject.put("bookId", x.getBookId());
            jsonObject.put("title", books.getTitle());
            jsonObject.put("imageUrl", books.getImageUrl());
            jsonObject.put("timeLimit", x.getTimeLimit());
            jsonObject.put("delay", x.getDelay());
            jsonObject.put("overdue", x.getOverdue());
            jsonObject.put("createdAt", x.getCreatedAt());
            jsonObject.put("returnAt", x.getReturnAt());
            jsonObject.put("updatedAt", x.getUpdatedAt());
            jsonObject.put("status", status);
            jsonObject.put("remarks", remarks);
            return jsonObject;
        }).collect(Collectors.toList());

        Collections.reverse(result);

        return JsonResult.success(result);
    }

    @GetMapping("/detail/{borrowId}")
    public JsonResult getBorrowDetail(@PathVariable Long borrowId) {
        Borrow one = borrowService.lambdaQuery().eq(Borrow::getBorrowId, borrowId).one();

        Books books = booksService.lambdaQuery().eq(Books::getBookId, one.getBookId()).one();

        boolean exists = scoreService.lambdaQuery()
                .eq(Score::getUserId, one.getUserId())
                .eq(Score::getBookId, one.getBookId())
                .exists();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("borrowId", one.getBorrowId());
        jsonObject.put("title", books.getTitle());
        jsonObject.put("author", books.getAuthor());
        jsonObject.put("publisher", books.getPublisher());
        jsonObject.put("summary", books.getSummary());
        jsonObject.put("imageUrl", books.getImageUrl());
        jsonObject.put("timeLimit", one.getTimeLimit());
        jsonObject.put("delay", one.getDelay());
        jsonObject.put("overdue", one.getOverdue());
        jsonObject.put("createdAt", one.getCreatedAt());
        jsonObject.put("returnAt", one.getReturnAt());
        jsonObject.put("updatedAt", one.getUpdatedAt());
        jsonObject.put("isScore", exists ? 1 : 0);

        return JsonResult.success(jsonObject);
    }

    @PostMapping("/add")
    public JsonResult add(@RequestBody String post, @CurrentUser CurrentUserPojo userPojo) {
        Long userId = userPojo.getUserId();
        JSONObject jsonObject = JSONObject.parseObject(post);
        Long bookId = Long.parseLong((String)jsonObject.get("bookId"));
        String date = (String)jsonObject.get("date");
        Date date1 = DateHelper.StringToDate(date);
        //System.out.println(date1.toString());

        Instant instant = date1.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        // atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
        LocalDate localDate = instant.atZone(zoneId).toLocalDate();
        long between = ChronoUnit.DAYS.between(LocalDate.now(), localDate);
        //System.out.println(between);
        borrowService.save(new Borrow(userId, bookId, (int) between,0,0));
        return JsonResult.success();
    }

    @GetMapping("/delay/{borrowId}")
    public JsonResult delay(@PathVariable Long borrowId, @CurrentUser CurrentUserPojo userPojo) {
        Long userId = userPojo.getUserId();
        Borrow one = borrowService.lambdaQuery().eq(Borrow::getBorrowId, borrowId).one();
        if (!Objects.equals(one.getUserId(), userId)){
            return JsonResult.error("没权限");
        }
        one.setTimeLimit(one.getTimeLimit()+7);
        one.setDelay(1);
        borrowService.updateById(one);
        return JsonResult.success();
    }

    @GetMapping("/return/{borrowId}")
    public JsonResult returnBook(@PathVariable Long borrowId, @CurrentUser CurrentUserPojo userPojo) {
        Long userId = userPojo.getUserId();
        Borrow one = borrowService.lambdaQuery().eq(Borrow::getBorrowId, borrowId).one();
        if (!Objects.equals(one.getUserId(), userId)){
            return JsonResult.error("没权限");
        }
        one.setReturnAt(LocalDateTime.now());
        borrowService.updateById(one);
        return JsonResult.success();
    }

}
